package com.ruoyi.smartai.service.impl;

import com.ruoyi.common.constant.CustomerPersonaAgents;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.smartai.config.MessageJob;
import com.ruoyi.smartai.service.IDynamicQuartzService;
import com.ruoyi.smartai.service.IPersonaAgentsService;
import com.ruoyi.smartai.utils.WhatsAPPUtils;
import com.ruoyi.system.domain.CustomerInfo;
import com.ruoyi.system.domain.FansInfo;
import com.ruoyi.system.domain.StandardScript;
import com.ruoyi.system.mapper.CustomerInfoMapper;
import com.ruoyi.system.mapper.FansInfoMapper;
import org.quartz.JobDataMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Service
public class PersonaAgentsServiceImpl implements IPersonaAgentsService {

    private static final Logger log = LoggerFactory.getLogger(DialogueServiceImpl.class);

    @Autowired
    private RedisCache redisCache;

    @Autowired(required = false)
    private IDynamicQuartzService dynamicQuartzService;

    @Autowired(required = false)
    private CustomerInfoMapper customerInfoMapper;

    @Override
    public CustomerPersonaAgents getPersonaAgentsByNumber(String customerNumber) {
        String keys = "persona:customer:" + customerNumber + ":agents";
        CustomerPersonaAgents agent = redisCache.getCacheObject(keys);
        try {
            CustomerInfo customerInfo = customerInfoMapper.selectUserByNumber(customerNumber);
            agent.setLinkStatus(customerInfo.getLinkStatus());
            redisCache.setCacheObject(keys, agent);
        } catch (Exception e) {

        }
        return agent;
    }

    @Override
    public int updateAgents(CustomerPersonaAgents agents) {
        CustomerInfo customerInfo = new CustomerInfo();
        String customerNumber = agents.getCustomerNumber();
        if (StringUtils.isNotNull(customerNumber)) {
            customerInfo.setContactNumber(customerNumber);
            if (StringUtils.isNotNull(agents.getLinkStatus())) {
                customerInfo.setLinkStatus(agents.getLinkStatus());
            }
            if (StringUtils.isNotNull(agents.getCity())) {
                customerInfo.setCityName(agents.getCity());
                updateCity(customerNumber, "city", agents.getCity());
            }

            if (StringUtils.isNotNull(agents.getTimeZone())) {
                updateCity(customerNumber, "citytime", agents.getTimeZone());
            }

            if (StringUtils.isNotNull(agents.getCustomerName())) {
                customerInfo.setContactName(agents.getCustomerName());
            }
            if (StringUtils.isNotNull(agents.getCharacterImage())) {
                putImagePath(agents.getCharacterImage(), customerNumber);
            }

            customerInfoMapper.updateUser(customerInfo);
            if (StringUtils.isNotNull(agents.getRestTime())) {
                morningMessageJob(customerNumber, agents.getRestTime());
            }
            String keys = "persona:customer:" + customerNumber + ":agents";
            redisCache.setCacheObject(keys, agents);
        }
        return 1;
    }

    private void putImagePath(String characterImage, String customerNumber) {
        Map<String, String> imageMap = new HashMap<>();
        String[] imagesText = characterImage.split("\n");
        for (String text : imagesText) {
            if (text.contains(":")) {
                String[] pic = text.split(":");
                imageMap.put(pic[0], pic[1]);
            }
        }
        String imageKey = "persona:customer:" + customerNumber + ":images";
        redisCache.setCacheObject(imageKey, imageMap);
    }


    private void updateCity(String customerNumber, String key, String value) {
        String keys = "persona:customer:" + customerNumber + ":";
        redisCache.setCacheObject(keys + key, value);
    }


    @Override
    public void morningMessageJob(String customerId, String startTime) {
        try {
            if (startTime.contains("-")) {
                String[] parts = startTime.split("-");
                //开始休息
                addMorningMessageJob(customerId, parts[0], true);
                //结束休息
                addMorningMessageJob(customerId, parts[1], false);

                setCustomerWorkStatus(customerId, startTime);
            }
        } catch (Exception e) {
            log.error("morningMessageJob Exception:" + e);
        }
    }

    /**
     * 根据客户ID和休息时间范围，判断当前是否为工作时间并设置状态
     *
     * @param customerId 客户ID
     * @param restTimeRange 休息时间范围，格式为"HH:mm-HH:mm"，例如"4:00-11:00"
     */
    @Override
    public void setCustomerWorkStatus(String customerId, String restTimeRange) {
        try {
            if (StringUtils.isEmpty(restTimeRange) || !restTimeRange.contains("-")) {
                log.error("休息时间格式错误，应为 'HH:mm-HH:mm' 格式，例如 '4:00-11:00'，当前值: {}", restTimeRange);
                return;
            }

            // 解析休息时间范围
            String[] timeRangeParts = restTimeRange.split("-");
            if (timeRangeParts.length != 2) {
                log.error("休息时间格式错误，无法分割为开始和结束时间，当前值: {}", restTimeRange);
                return;
            }

            String restStartTime = timeRangeParts[0].trim();
            String restEndTime = timeRangeParts[1].trim();

            // 将时间字符串转换为小时和分钟
            String[] restStartParts = restStartTime.split(":");
            String[] restEndParts = restEndTime.split(":");

            if (restStartParts.length != 2 || restEndParts.length != 2) {
                log.error("时间格式错误，应为 'HH:mm'，当前值: {}", restTimeRange);
                return;
            }

            int restStartHour = Integer.parseInt(restStartParts[0]);
            int restStartMinute = Integer.parseInt(restStartParts[1]);
            int restEndHour = Integer.parseInt(restEndParts[0]);
            int restEndMinute = Integer.parseInt(restEndParts[1]);

            // 转换为分钟表示
            int restStartInMinutes = restStartHour * 60 + restStartMinute;
            int restEndInMinutes = restEndHour * 60 + restEndMinute;

            // 获取当前时间
            Calendar now = Calendar.getInstance();
            int currentHour = now.get(Calendar.HOUR_OF_DAY);
            int currentMinute = now.get(Calendar.MINUTE);
            int currentTimeInMinutes = currentHour * 60 + currentMinute;

            // 判断当前是否为休息时间
            boolean isCurrentlyRestTime;

            // 处理跨天的情况（如果休息结束时间小于开始时间，则认为跨天）
            if (restEndInMinutes < restStartInMinutes) {
                // 跨天情况：例如 22:00-6:00
                isCurrentlyRestTime = currentTimeInMinutes >= restStartInMinutes || currentTimeInMinutes < restEndInMinutes;
            } else {
                // 同一天内：例如 4:00-11:00
                isCurrentlyRestTime = currentTimeInMinutes >= restStartInMinutes && currentTimeInMinutes < restEndInMinutes;
            }

            // 设置工作状态（0表示工作，1表示休息）
            boolean isCurrentlyWorkTime = !isCurrentlyRestTime;
            redisCache.setCacheObject("persona:customer:" + customerId + ":work", isCurrentlyWorkTime ? 0 : 1);

            log.info("客户 {} 的工作状态已设置为: {}，休息时间范围: {}",
                    customerId, isCurrentlyWorkTime ? "工作中" : "休息中", restTimeRange);

        } catch (Exception e) {
            log.error("设置客户 {} 工作状态时发生异常: {}", customerId, e.getMessage(), e);
        }
    }

    public void addMorningMessageJob(String customerId, String time, boolean isWork) {
        try {
            // 将字符串时间转换为 Cron 表达式
            String[] parts = time.split(":");
            int hour = Integer.parseInt(parts[0]);
            int minute = Integer.parseInt(parts[1]);

            String cronExpression = String.format("0 %d %d * * ?", minute, hour);

            // 创建任务参数
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("customerId", customerId);
            jobDataMap.put("isOnWork", isWork);

            String jobName = "morningJob_" + customerId + "-" + (isWork ? 1 : 0);
            String jobGroup = "customerGroup";
            String trigerName = "onWorkJob_" + customerId + "-" + (isWork ? 1 : 0);

            dynamicQuartzService.deleteJob(jobName, jobGroup);
            dynamicQuartzService.addJob(jobName, jobGroup, trigerName, "customerTriggerGroup", MessageJob.class, cronExpression, jobDataMap);

        } catch (Exception e) {
            log.error("addMorningMessageJob Exception:" + e);
        }
    }
}
